<template>
  <el-card class="form-container" shadow="never">
    <el-form :model="book" :rules="rules" ref="book" label-width="80px">
      <el-form-item label="书籍名称" prop="name">
        <el-input v-model="book.name" placeholder="请输入书籍名称"></el-input>
      </el-form-item>
      <el-form-item label="分类">
        <el-cascader @change="cateChange" v-model="book.cateIds" :options="bookCategories" :props="cateOption"
                     filterable>
        </el-cascader>
      </el-form-item>
      <el-form-item label="科目">
        <el-radio-group v-model="book.subjectId">

          <el-radio :key="item.id" v-for="item in subjects" :label="item.id">{{ item.name }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="封面图片" prop="img">
        <ImgClip :width="337" :height="342" :fixed="[0.938438, 1]" style="cursor: pointer" :default-poster="imgUrl"
                 @sendChangePoster="sendImgFun"/>
      </el-form-item>
      <el-row>
        <el-col :sm="24" :md="12">
          <el-form-item label="ISBN" prop="isbn">
            <el-input v-model="book.isbn" placeholder="请输入书籍ISBN"></el-input>
          </el-form-item>
        </el-col>
        <el-col :sm="24" :md="12">
          <el-form-item label="作者" prop="isbn">
            <el-input v-model="book.author" placeholder="请输入书籍作者"></el-input>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row>
        <el-col :lg="6" :md="12" :sm="24">
          <el-form-item label="价格" prop="price">
            <el-input v-model="book.price" placeholder="请输入书籍价格"></el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="6" :md="12" :sm="24">
          <el-form-item label="数量" prop="count">
            <el-input v-model="book.count" placeholder="请输入书籍数量">
              <template slot="append">本</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="6" :md="12" :sm="24">
          <el-form-item label="字数" prop="words">
            <el-input v-model="book.words" placeholder="请输入书籍字数">
              <template slot="append">千字</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="6" :md="12" :sm="24">
          <el-form-item label="版次" prop="edition">
            <el-input v-model="book.edition" placeholder="请输入书籍版次">
              <template slot="append">版</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>


      <el-row>
        <el-col :lg="6" :md="12" :sm="24">
          <el-form-item label="优先级" prop="sort">
            <el-input-number v-model="book.sort" :min="0" :max="100"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :lg="6" :md="12" :sm="24">
          <el-form-item label="装订">
            <el-select
              v-model="book.binding"
              filterable
              allow-create
              default-first-option
              placeholder="请选择或填写书籍装订">
              <el-option
                v-for="item in binding"
                :label="item.label" :key="item.value" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :lg="6" :md="12" :sm="24">
          <el-form-item label="图书规格">
            <el-input v-model="book.spec" placeholder="例：789x1090mm"/>
          </el-form-item>
        </el-col>
        <el-col :lg="6" :md="12" :sm="24">
          <el-form-item label="图书开本">
            <el-input v-model="book.sheet" placeholder="">
              <template slot="append">开</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="状态">
        <el-radio-group v-model="book.state">
          <el-radio :label="1">上架</el-radio>
          <el-radio :label="0">下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="book.recommend">
          <el-radio :label="1">推荐</el-radio>
          <el-radio :label="0">不推荐</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="内容" prop="description">
        <tinymce ref="content" v-model="book.description" style="min-width: 720px"/>
      </el-form-item>
      <el-row>
        <el-col :sm="24" :md="12">
          <el-form-item label="添加普通附件">
            <upload
              :action="action"
              :data="chunkData"
              :on-success="handleSuccess1"
              :on-remove="handleRemove1"
              :chunk-size="1024 * 1024 * 3"
              :thread="4"
              :on-error="errorHandler"
              :file-list="fileList"
              :headers="header"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">上传图书附件文件</div>
            </upload>
          </el-form-item>
        </el-col>
        <el-col :sm="24" :md="12">
          <el-form-item label="添加音频附件">
            <upload
              :action="action"
              :data="chunkData"
              :on-remove="handleRemove2"
              :on-success="handleSuccess2"
              :chunk-size="1024 * 1024 * 3"
              :thread="4"
              :headers="header"
              :before-upload="filterMp3"
              :on-error="errorHandler"
              :file-list="audioList"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传mp3文件</div>
            </upload>
          </el-form-item>
        </el-col>
      </el-row>
      <div ref="t" style="width: 100%;display: flex;justify-content: center;flex-direction: row">
        <div>
          <el-button style="margin: 0 auto;width: fit-content" type="primary" @click.prevent.native="handle">提交
          </el-button>
          <el-button style="margin: 0 auto;width: fit-content" type="" @click.prevent.native="reset">重置
          </el-button>
        </div>
      </div>
    </el-form>
  </el-card>
</template>

<script>
import tinymce from "@/components/Tinymce"
import ImgClip from "@/components/ImgClip"
import {dataURItoBlob, getBaseUrl} from "@/utils"
import upload from "@/components/uploadChunk"
import {getToken} from '@/utils/auth'
import {getCategoryTree} from "@/api/productCate";

import {addBook, getBook, getSubjectList} from "@/api/book";
import {getCategoryListAll, updateBook} from "@/api/product";

const defaultBook = {
  name: '',
  count: 999,
  isbn: '',
  price: 0,
  spec: '',
  binding: '',  //装订
  sort: 0,
  sheet: '', //印张 开本
  words: 0, //字数 单位 千
  edition: '', //版次
  description: '' //书籍描述
  , cateIds: []
  , state: 1
  , author: ''  //作者
  , subjectId: 0
  , categoryId: 0
  , files: []
  , audios: []
  , imgFile: null
  , recommend: 0
}
export default {
  name: "ProductDetail",
  components: {
    ImgClip,
    tinymce,
    upload
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      cateList: [],
      binding: [
        {
          label: '平装',
          value: '平装'
        },{
          label: '胶装',
          value: '胶装'
        },{
          label: '精装',
          value: '精装'
        },
      ],
      bookId: 0,
      header: {
        Authorization: getToken()
      },
      action: getBaseUrl() + '/upload',
      book: Object.assign({}, defaultBook),
      imgFileName: '',
      fileList: [],
      audioList: [],
      rules: {
        name: [
          {required: true, message: '请输入书籍名称', trigger: 'blur'}
        ]
      },
      imgUrl: '',
      bookCategories: [],
      cateOption: {
        // checkStrictly: true,
        value: 'id',
        label: 'name'
      },
      subjects: []
    }
  },
  methods: {
    sendImgFun(base64) {
      if (base64)
        this.book.imgFile = dataURItoBlob(base64.base64)
      this.imgFileName = base64.fileName
    },
    handle() {
      this.$refs.book.validate(valid => {
        if (valid) {
          //添加书籍
          let msg = '添加商品书籍, 是否继续?'
          if(this.isEdit)
            msg = '修改商品书籍, 是否继续?'
          this.$confirm(msg, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const formData = new FormData();
            if (this.book.img) {
              formData.set("img", this.book.imgFile, this.imgFileName)
            }
            formData.set("name", this.book.name)
            formData.set("price", this.book.price)
            formData.set("sort", this.book.sort)
            formData.set("binding", this.book.binding)
            if (this.book.isbn) {
              formData.set("isbn", this.book.isbn)
            }
            if (this.book.files) {
              formData.set("files", this.book.files)
            }
            if (this.book.audios) {
              formData.set("audios", this.book.audios)
            }
            if (this.book.imgFile != null) {
              formData.set("imgFile", this.book.imgFile, this.imgFileName)
            }
            if (this.book.words !== 0) {
              formData.set("words", this.book.words)
            }
            formData.set("description", this.book.description)
            if (this.book.author) {
              formData.set("author", this.book.author)
            }
            if (this.book.edition) {
              formData.set("edition", this.book.edition)
            }
            if (this.book.subjectId) {
              formData.set("subjectId", this.book.subjectId)
            }
            if (this.book.categoryId) {
              formData.set("categoryId", this.book.categoryId)
            }
            if (this.book.sheet) {
              formData.set("sheet", this.book.sheet)
            }
            if (this.book.spec) {
              formData.set("spec", this.book.spec)
            }
            formData.set("state", this.book.state)
            formData.set("count", this.book.count)
            formData.set("adminId", this.book.adminId)
            if (!this.isEdit) {
              //添加书籍
              addBook(formData).then((resp) => {
                if (resp) {
                  this.$message({
                    type: 'success',
                    message: '添加成功!'
                  });
                }
              })
            } else {
              updateBook(this.bookId, formData).then(res => {
                if (res) {
                  this.$message({
                    type: 'success',
                    message: '修改成功!'
                  });
                }
              })
            }

          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消添加'
            });
          });

        } else {
          console.log('参数不合法!')
          return false
        }
      })
    },
    reset() {
      location.reload();
    },
    chunkData(option) {
      return {
        fileSize: option.fileSize, // 总文件大小
        chunkTotal: option.chunkTotal, // 所有切片数量
        index: option.chunkIndex,// 当前切片下标
        chunkHash: option.chunkHash, // 单个切片hash
        fileName: option.fileName, // 文件名
        fileHash: option.fileHash, // 整个文件hash
        chunkOneSize: option.chunkSize
      }
    },
    handleSuccess1(response, file, fileList) {
      this.book.files.push(response.data.file.id);
      console.log(this.book)
    },
    handleSuccess2(response, file, fileList) {
      this.book.audios.push(response.data.file.id);

    },
    handleRemove1(file, fileList) {
      const id = file.response.data.file.id
      console.log(this.files)
      const index = this.book.files.indexOf(id);
      if (index !== -1) {
        this.book.files.splice(index, 1);
      }

    },
    handleRemove2(file, fileList) {
      const id = file.response.data.file.id
      const index = this.book.audios.indexOf(id);
      if (index !== -1) {
        this.book.audios.splice(index, 1);
      }
    },
    filterMp3(file) {
      const ext = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = ext === 'mp3'
      if (!extension) {
        this.$message({
          message: "音频附件只能是mp3格式！",
          type: 'error'
        })
      }
      return extension;
    },
    errorHandler(response, file, fileList) {
      console.log(response, file, fileList)
    },
    getCategories() {
      getCategoryTree().then(
        res => {
          this.bookCategories = this.handleEmptyData(res.data)
        }
      )
    },
    // 递归处理children空数组情况
    handleEmptyData(data) {
      for (let i = 0; i < data.length; i++) {
        if (!data[i].children || data[i].children.length === 0) {
          data[i].children = undefined; // child若为空数组，则将child设为undefined
        } else {
          this.handleEmptyData(data[i].children); // child若不为空数组，则继续递归
        }
      }
      return data;
    },
    getSubjectList() {
      getSubjectList(this.book.categoryId).then(
        res => {
          // console.log(res.data);
          this.subjects = res.data;
        }
      )
    },
    cateChange(val) {
      this.book.categoryId = val[val.length - 1]
      this.getSubjectList()
      this.book.subjectId = null
    },
    appendCateFather(cateArr, val) {
      const filter = this.cateList.filter(item => item.id === val);
      if (filter && filter.length > 0 && filter[0] !== undefined) {
        cateArr.unshift(filter[0].id);
        if (filter[0].parentId !== 0) {
          this.appendCateFather(cateArr, filter[0].parentId)
        }
      }
    },
  },
  beforeMount() {
    this.book.adminId = this.$store.getters.admin.id;
    this.imgUrl = this.$store.getters.store + "group1/M00/00/00/wKhwgWGQjKCACMr_AAARtnbBaRA065.png";
    this.getCategories();
    if (this.$route.query.id) {
      this.bookId = this.$route.query.id;
      getBook(this.bookId).then(res => {
        // console.log(res.data)
        this.imgUrl = this.$store.getters.store + res.data.img
        this.book = {...defaultBook, ...res.data}
        delete this.book.img

      }).then(() => {
        getCategoryListAll().then(res => {
          this.cateList = res.data;
          const cateArr = []
          const filter = this.cateList.filter(item => item.id === this.book.categoryId);
          if (filter && filter.length > 0 && filter[0] !== undefined) {
            cateArr.unshift(filter[0].id);
            if (filter[0].parentId !== 0) {
              this.appendCateFather(cateArr, filter[0].parentId)
            }
          }
          this.book.cateIds = cateArr
          this.getSubjectList()
        })
      })
    }


  }

}
</script>

<style scoped>
.form-container {
  width: 80%;
  left: 180px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 300px;
  height: 181px;
  display: block;
}
</style>
